package by.ad.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AppspotRedirectFilter
  implements Filter 
{
  public void init(final FilterConfig filterConfig)
    throws ServletException
  {
    location = filterConfig.getInitParameter("Location");
  }

  public void doFilter(final ServletRequest req, final ServletResponse resp,
    final FilterChain filterChain)
      throws IOException, ServletException
  {
    if (req instanceof HttpServletRequest && resp instanceof HttpServletResponse) {
      final HttpServletRequest request = (HttpServletRequest) req;
      final HttpServletResponse response = (HttpServletResponse) resp;
      
      if (request.getServerName().toLowerCase().endsWith(".appspot.com") &&
        // do redirect GET only
        request.getMethod().equalsIgnoreCase("GET") &&
        // do not redirect https
        !request.getScheme().equalsIgnoreCase("https") &&
        // do not redirect beta versions (started with numbers)
        request.getServerName().matches("^[0-9]+"))
      {
        final String q = request.getQueryString();
        response.setHeader("Location", location + request.getRequestURI() + 
          ((q != null && q.length() != 0) ? ("?" + q) : "" ));
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        
        // TODO store log to DB and show report on /techstat page
        
        return;
      }
    }
      
    filterChain.doFilter(req, resp);    
  }

  public void destroy() {}
    
  private String location; 
}
